package com.suning.sawp.web.controller;

import java.security.Principal;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.suning.nsfsmm.order.rsfservice.ExceptionOrderService;
import com.suning.nsfsmm.order.rsfservice.dto.ExpCmmdtyDetail;
import com.suning.nsfsmm.order.rsfservice.dto.ExpCmmdtyItem;
import com.suning.nsfsmm.order.rsfservice.dto.ExpOrderDayDetail;
import com.suning.nsfsmm.order.rsfservice.dto.ExpOrderDetail;
import com.suning.nsfsmm.order.rsfservice.dto.ExpOrderDetailItem;
import com.suning.nsfsmm.order.rsfservice.dto.ExpOrderQueryCmmdtyDto;
import com.suning.nsfsmm.order.rsfservice.dto.ExpOrderQueryDetailDto;
import com.suning.rsf.consumer.ServiceLocator;
import com.suning.sawp.constants.ClerkConstants;
import com.suning.sawp.constants.ErrorCodeConstants;
import com.suning.sawp.dto.bi.BiSaleAmountDto;
import com.suning.sawp.dto.common.ReturnMsg;
import com.suning.sawp.dto.fastsale.ExpCommDto;
import com.suning.sawp.dto.fastsale.ExpCommIndexResult;
import com.suning.sawp.dto.fastsale.ExpCommOrderDetailDto;
import com.suning.sawp.dto.fastsale.ExpCommOrderDetailResult;
import com.suning.sawp.dto.fastsale.ExpOrderDayDetailDto;
import com.suning.sawp.dto.fastsale.ExpOrderIndexResult;
import com.suning.sawp.dto.fastsale.ExpOrderItemDto;
import com.suning.sawp.dto.mainpush.StoreManDto;
import com.suning.sawp.intf.storeman.StoreManService;
import com.suning.sawp.web.exception.MyGsonView;

@Controller
@RequestMapping("/fastSale")
public class FastSaleExpOrderController extends DjBaseController {
    
    private static final Logger LOGGER = LoggerFactory.getLogger(FastSaleExpOrderController.class);

    @Resource
    StoreManService storeManService;
    
    private ExceptionOrderService exceptionOrderService = ServiceLocator.getService(ExceptionOrderService.class, null);
    
    /**
     * 
     * 功能描述: <br>
     * 〈功能详细描述〉
     *  卡单首页订单维度查询
     * @param principal
     * @param page
     * @param pageSize
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/indexOrderQuery.do")
    public MyGsonView indexOrderQuery(Principal principal, Integer page, Integer pageSize) {
        Object[] args = {principal.getName(), page, pageSize};
        LOGGER.info("indexCommQuery.do params; staffId:{}, page:{}, pageSize:{}", args);
        ReturnMsg<ExpOrderIndexResult> retMsg = new ReturnMsg<ExpOrderIndexResult>();
        // 查询店员信息
        StoreManDto manDto = storeManService.queryStoreManAttachInfo(principal.getName());
        if (checkParams(manDto)) {
            // 只有店长或者督导角色才能查询
            ExpOrderQueryDetailDto expOrderQueryDetailDto = new ExpOrderQueryDetailDto();
            expOrderQueryDetailDto.setStoreCode(manDto.getStoreCode());
            expOrderQueryDetailDto.setPage(page);
            expOrderQueryDetailDto.setPageSize(pageSize);
            ExpOrderDetail detail = null;
            try {
                detail = exceptionOrderService.queryExpOrderSummaryDetail(expOrderQueryDetailDto);
            } catch (Exception e) {
                LOGGER.error("invoke exceptionOrderService.queryExpOrderSummaryDetail error, params:{}", expOrderQueryDetailDto, e);
            }
            if (detail != null && "Y".equals(detail.getIsSuccess())) {
                // 组装前端所需数据
                ExpOrderIndexResult result = new ExpOrderIndexResult();
                result.setOrderSumQty(getQtyNumStr(detail.getOrderSumQty()));
                result.setUnsolvedCmmdtyQty(getQtyNumStr(detail.getUnsolvedCmmdtyQty()));
                result.setUnsolvedOrderQty(getQtyNumStr(detail.getUnsolvedOrderQty()));
                result.setLoseAmount(BiSaleAmountDto.valueOf(detail.getLoseAmount()));
                int orderNum = 0;
                List<ExpOrderDayDetailDto> expOrderDayDetailDtos = new ArrayList<ExpOrderDayDetailDto>();
                if (CollectionUtils.isNotEmpty(detail.getExpOrderDayDetails())) {
                    for (ExpOrderDayDetail dayDetail : detail.getExpOrderDayDetails()) {
                        ExpOrderDayDetailDto dayDetailDto = new ExpOrderDayDetailDto();
                        dayDetailDto.setDate(dayDetail.getDate());
                        dayDetailDto.setUnsolvedOrderQty(dayDetail.getUnsolvedOrderQty());
                        List<ExpOrderItemDto> itemDtos = new ArrayList<ExpOrderItemDto>();
                        if (CollectionUtils.isNotEmpty(dayDetail.getExpOrderItems())) {
                            for (ExpOrderDetailItem detailItem : dayDetail.getExpOrderItems()) {
                                ExpOrderItemDto dto = new ExpOrderItemDto();
                                dto.setBarcode(detailItem.getBarcode());
                                dto.setCmmdtyCode(detailItem.getCmmdtyCode());
                                dto.setCmmdtyName(detailItem.getCmmdtyName());
                                dto.setOrderNo(detailItem.getOrderNo());
                                dto.setQty(detailItem.getQty());
                                dto.setReason(detailItem.getReason());
                                dto.setReasonCode(detailItem.getReasonCode());
                                dto.setSaleTime(detailItem.getSaleTime());
                                dto.setTotalAmount(getAmountStr(detailItem.getTotalAmount()));
                                
                                itemDtos.add(dto);
                                orderNum++;
                            }
                            dayDetailDto.setExpOrderItems(itemDtos);
                        }
                        expOrderDayDetailDtos.add(dayDetailDto);
                    }
                }
                result.setExpOrderDayDetails(expOrderDayDetailDtos);
                result.setOrderNum(orderNum);
                retMsg.setData(result);
            } else {
                LOGGER.warn("exceptionOrderService.queryExpOrderSummaryDetail fail, params:{}", expOrderQueryDetailDto);
                retMsg.setError(ErrorCodeConstants.ERR_0042);
            }
        } else {
            retMsg.setError(ErrorCodeConstants.ERR_0035);
        }
        
        return setGsonView(retMsg);
    }
    
    /**
     * 
     * 功能描述: <br>
     * 〈功能详细描述〉
     * 卡单异常解决方案提示
     * @param principal
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/solveTips.do")
    public MyGsonView solveTips(Principal principal, String reasonCode) {
        ReturnMsg<List<String>> retMsg = new ReturnMsg<List<String>>();
        // 查询店员信息
        StoreManDto manDto = storeManService.queryStoreManAttachInfo(principal.getName());
        if (checkParams(manDto)) {
            List<String> list = null;
            try {
                list = exceptionOrderService.queryErrorSolution(reasonCode);
            } catch (Exception e) {
                LOGGER.error("invoke exceptionOrderService.queryErrorSolution error, params:{}", reasonCode, e);
                retMsg.setError(ErrorCodeConstants.ERR_0042);
            }
            
            retMsg.setData(list);
        } else {
            retMsg.setError(ErrorCodeConstants.ERR_0035);
        }
        
        return setGsonView(retMsg);
    }
    
    /**
     * 
     * 功能描述: <br>
     * 〈功能详细描述〉
     * 卡单首页商品维度查询
     * @param principal
     * @param page
     * @param pageSize
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/indexCommQuery.do")
    public MyGsonView indexCommQuery(Principal principal, Integer page, Integer pageSize) {
        Object[] args = {principal.getName(), page, pageSize};
        LOGGER.info("indexCommQuery.do params; staffId:{}, page:{}, pageSize:{}", args);
        ReturnMsg<ExpCommIndexResult> retMsg = new ReturnMsg<ExpCommIndexResult>();
        // 查询店员信息
        StoreManDto manDto = storeManService.queryStoreManAttachInfo(principal.getName());
        if (checkParams(manDto)) {
            ExpOrderQueryCmmdtyDto expOrderQueryCmmdtyDto = new ExpOrderQueryCmmdtyDto();
            expOrderQueryCmmdtyDto.setPage(page);
            expOrderQueryCmmdtyDto.setPageSize(pageSize);
            expOrderQueryCmmdtyDto.setStoreCode(manDto.getStoreCode());
            ExpCmmdtyDetail cmmdtyDetail = null;
            try {
                cmmdtyDetail = exceptionOrderService.queryExpCmmdtyDetail(expOrderQueryCmmdtyDto);
            } catch (Exception e) {
                LOGGER.error("invoke exceptionOrderService.queryExpCmmdtyDetail error, params:{}", expOrderQueryCmmdtyDto, e);
            }
            if (null != cmmdtyDetail && "Y".equals(cmmdtyDetail.getIsSuccess())) {
                // 组装数据
                ExpCommIndexResult result = new ExpCommIndexResult();
                result.setUnsolvedCmmdtyQty(getQtyNumStr(cmmdtyDetail.getUnsolvedCmmdtyQty()));
                List<ExpCommDto> expCmmdites = new ArrayList<ExpCommDto>();
                if (CollectionUtils.isNotEmpty(cmmdtyDetail.getExpCmmdites())) {
                    for (ExpCmmdtyItem item : cmmdtyDetail.getExpCmmdites()) {
                        ExpCommDto commDto = new ExpCommDto();
                        commDto.setBarcode(item.getBarcode());
                        commDto.setCmmdtyCode(item.getCmmdtyCode());
                        commDto.setCmmdtyName(item.getCmmdtyName());
                        commDto.setLoseAmount(getAmountStr(item.getLoseAmount()));
                        commDto.setLoseQty(item.getLoseQty());
                        commDto.setUnsolvedCmmdtyQty(item.getUnsolvedCmmdtyQty());
                        commDto.setUnsolvedOrderQty(item.getUnsolvedOrderQty());
                        
                        expCmmdites.add(commDto);
                    }
                }
                result.setExpCmmdites(expCmmdites);
                retMsg.setData(result);
            } else {
                LOGGER.warn("exceptionOrderService.queryExpCmmdtyDetail fail, params:{}, cmmdtyDetail:{}", expOrderQueryCmmdtyDto, cmmdtyDetail);
                retMsg.setError(ErrorCodeConstants.ERR_0042);
            }
        } else {
            retMsg.setError(ErrorCodeConstants.ERR_0035);
        }
        
        return setGsonView(retMsg);
    }
    
    /**
     * 
     * 功能描述: <br>
     * 〈功能详细描述〉
     * 卡单商品相关订单详情列表
     * @param principal
     * @param cmmdtyCode
     * @param page
     * @param pageSize
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/commOrderDetails.do")
    public MyGsonView commOrderDetails(Principal principal, String cmmdtyCode, Integer page, Integer pageSize) {
        Object[] args = {principal.getName(), cmmdtyCode, page, pageSize};
        LOGGER.info("commOrderDetails.do params; staffId:{}, cmmdtyCode:{}, page:{}, pageSize:{}", args);
        ReturnMsg<ExpCommOrderDetailResult> retMsg = new ReturnMsg<ExpCommOrderDetailResult>();
        // 查询店员信息
        StoreManDto manDto = storeManService.queryStoreManAttachInfo(principal.getName());
        if (checkParams(manDto)) {
            ExpOrderQueryDetailDto expOrderQueryDetailDto = new ExpOrderQueryDetailDto();
            expOrderQueryDetailDto.setStoreCode(manDto.getStoreCode());
            expOrderQueryDetailDto.setCmmdtyCode(cmmdtyCode);
            expOrderQueryDetailDto.setPage(page);
            expOrderQueryDetailDto.setPageSize(pageSize);
            ExpOrderDetail detail = null;
            try {
                detail = exceptionOrderService.queryExpOrderSummaryDetail(expOrderQueryDetailDto);
            } catch (Exception e) {
                LOGGER.error("invoke exceptionOrderService.queryExpOrderSummaryDetail error, params:{}", expOrderQueryDetailDto, e);
            }
            if (detail != null && "Y".equals(detail.getIsSuccess())) {
                ExpCommOrderDetailResult result = new ExpCommOrderDetailResult();
                
                result.setLoseAmount(getAmountStr(detail.getLoseAmount()));
                result.setLoseSumQty(getQtyNumStr(detail.getLoseSumQty()));
                result.setUnsolvedCmmdtyQty(getQtyNumStr(detail.getUnsolvedCmmdtyQty()));
                result.setUnsolvedOrderQty(getQtyNumStr(detail.getUnsolvedOrderQty()));
                List<ExpCommOrderDetailDto> expOrderDayDetails = new ArrayList<ExpCommOrderDetailDto>();
                if (CollectionUtils.isNotEmpty(detail.getExpOrderDayDetails())) {
                    for (ExpOrderDayDetail dayDetail : detail.getExpOrderDayDetails()) {
                        String date = dayDetail.getDate();
                        if (CollectionUtils.isNotEmpty(dayDetail.getExpOrderItems())) {
                            for (ExpOrderDetailItem detailItem : dayDetail.getExpOrderItems()) {
                                ExpCommOrderDetailDto dto = new ExpCommOrderDetailDto();
                                dto.setDate(date);
                                dto.setOrderNo(detailItem.getOrderNo());
                                dto.setQty(detailItem.getQty());
                                dto.setReason(detailItem.getReason());
                                dto.setReasonCode(detailItem.getReasonCode());
                                dto.setSaleTime(detailItem.getSaleTime());
                                dto.setTotalAmount(getAmountStr(detailItem.getTotalAmount()));
                                expOrderDayDetails.add(dto);
                                
                                result.setBarcode(detailItem.getBarcode());
                                result.setCmmdtyCode(detailItem.getCmmdtyCode());
                                result.setCmmdtyName(detailItem.getCmmdtyName());
                            }
                        }
                    }
                }
                result.setExpOrderDayDetails(expOrderDayDetails);
                retMsg.setData(result);
            } else {
                LOGGER.warn("commOrderDetails.do exceptionOrderService.queryExpOrderSummaryDetail fail, params:{}", expOrderQueryDetailDto);
                retMsg.setError(ErrorCodeConstants.ERR_0042);
            }
        } else {
            retMsg.setError(ErrorCodeConstants.ERR_0035);
        }
        
        return setGsonView(retMsg);
    }
    
    /**
     * 
     * 功能描述: 校验督导和店长身份<br>
     * 〈功能详细描述〉
     *
     * @param manDto
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private boolean checkParams(StoreManDto manDto) {
        if (null != manDto && StringUtils.isNotBlank(manDto.getStoreCode()) 
                && (ClerkConstants.STORE_KEEPER.equals(manDto.getPositionId())
                || ClerkConstants.SALE_GUIDE.equals(manDto.getPositionId())
                || ClerkConstants.CATE_MANAGER.equals(manDto.getPositionId()))) {
            return true;
        } else {
            return false;
        }
    }
    
    /**
     * 
     * 功能描述: 数字转字符<br>
     * 〈功能详细描述〉
     *
     * @param decimal
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private String getQtyNumStr(String decimal) {
        return StringUtils.isBlank(decimal) ? "0" : decimal;
    }
    
    /**
     * 
     * 功能描述: 金额数字转字符<br>
     * 〈功能详细描述〉
     *
     * @param decimal
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private String getAmountStr(String decimal) {
        return StringUtils.isBlank(decimal) ? "0.00" : decimal;
    }
    
}
